/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Indhold+ for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.digiform;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import dk.redia.digiform.model.CoverUrlCache;
import dk.redia.digiform.model.DigiformObject;
import dk.redia.lib.log.Log;
import dk.redia.lib.net.ImageCache;

public class BrowserActivity extends Activity {

	public static final String EXTRA_URL = "url";
	private static final String logTag = "BrowserActivity";

	private DigiformObject digiformObject;
	private TextView creatorTextView;
	private TextView titleTextView;
	private ImageView coverImageView;
	private WebView webView;
	private Handler handler;
	private Date lastInteractionTime;
	private ProgressBar webPageLoadingProgressBar;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browser);
		handler = new Handler();
		lastInteractionTime = new Date();
		// Ensure that screen doesn't get turned off
		getWindow().addFlags(
				android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		String url = getIntent().getStringExtra(EXTRA_URL);
		digiformObject = DigiformObject.lookCurrent();

		webView = (WebView) findViewById(R.id.browserWebView);
		creatorTextView = (TextView) findViewById(R.id.browserCreatorTextView);
		titleTextView = (TextView) findViewById(R.id.browserTitleTextView);
		coverImageView = (ImageView) findViewById(R.id.browserCoverImageView);
		webPageLoadingProgressBar = (ProgressBar)findViewById(R.id.progressBar1);
		webPageLoadingProgressBar.setAlpha(0.5f);

		if (url == null) {
			Log.e(logTag, "No URL provided to browser activity");
			finish();
		}

		if (digiformObject == null) {
			Log.e(logTag, "No current digiform object set");
			finish();
		}
		try {
			new URL(url);
		} catch (MalformedURLException e) {
			Log.e(logTag, "URL provided is invalid: " + e.getMessage());
			finish();
		}
		if(url.endsWith(".pdf")){
			url = "http://docs.google.com/gview?embedded=true&url="+url;
			webView.getSettings().setJavaScriptEnabled(true);
		}
		
		webView.loadUrl(url);

		// This is necessary to intercept clicks in the webview
		// By default clicking a link in a webview opens the Android
		// default URL handling activity, which will normally be
		// the built-in Android browser.
		// We don't want that.
		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				webView.loadUrl(url);
				resetIdleTimer();
				return true;
			}
			
			public void onPageFinished(WebView view, String url) {
				Log.d(logTag, "Loaded: " + url);
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged (WebView view, int newProgress) {
				if(newProgress == 100) {
					webPageLoadingProgressBar.setVisibility(View.INVISIBLE);
				}
			}
		});

		titleTextView.setText(digiformObject.getRecord().getTitle());
		creatorTextView.setText(digiformObject.getRecord().getCreator());
		// No need to request that the cache fetch anythin,
		// as ResourceOverviewActivity will have ensured that
		// if a cover is available for the current resource,
		// will already be in the cache
		String coverUrl = CoverUrlCache.getInstance().getCoverUrl(
				digiformObject.getRecord().getFaustId());
		Log.d(logTag, "Detected cover URL " + coverUrl);
		if (coverUrl != null && coverUrl != "") {
			try {
				ImageCache.getInstance().loadImage(new URL(coverUrl),
						coverImageView, null, 154, 241);
			} catch (MalformedURLException e) {
				Log.e(logTag, "Invalid cover URL " + coverUrl + " found");
			}
		}
		startIdleTimer();

	}

	private void resetIdleTimer() {
		lastInteractionTime = new Date();
	}

	private void idleCheck() {
		long idleTimeoutTime = lastInteractionTime.getTime() + 1000 * 60 * 2;
		long currentTime = System.currentTimeMillis();
		Log.d(logTag, "Idle UI timeout in " + (idleTimeoutTime - currentTime)
				+ " millis");
		if (idleTimeoutTime < currentTime) {
			// Idle time expired, close UI and go back to front page
			finish();
		} else {
			startIdleTimer();
		}
	}

	private void startIdleTimer() {
		Log.d(logTag, "Starting idle UI checker");
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				BrowserActivity.this.idleCheck();

			}
		}, 1000 * 60);
	}

	public void onBackButtonClicked(View v) {
		finish();
		//overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}

}
